# -*- coding: utf-8 -*-
# @Author : zhaochen
# @Date   : 2019/1/22
# @File   : IC18_PastLoanCardQuasiMaxConOvduMons.py
# @E-mail : zhaochen@bbdservice.com

'''eof
name:过去五年贷款和（准）贷记卡最长连续逾期或透支月数
code:IC18_PastLoanCardQuasiMaxConOvduMons_2D
tableName:
columnName:
groups:个人征信模块
dependencies:IC_DSJ_2D
type:常用指标
datasourceType:在线指标
description:
eof'''

import json
import sys
import re
import datetime
import pandas as pd

reload(sys)
sys.setdefaultencoding('utf-8')

null_type_list = ['', ' ', None, 'null', 'Null', 'NULL', '/', '-', '--']


def getTable(data, tableName, occurTimes, iteratorTimes):
    '''
        获取表信息
        :param data:表上层的字典对象
        :param tableName:表的名字
        :param occurTimes:表出现的次数，如果是0代表此表可以不出现，如果是1代表此表必须出现
        :param iteratorTimes:下级字段出现的次数，如果是0代表下级字段可以不出现，如果是1代表下级字段必须出现
        :return:该表全部数据  返回[{}]为异常缺失，返回0为正常缺失，其他返回正常数组
        '''
    try:
        table = data.get(tableName)
        if occurTimes == 0:
            if table is None or (table == "" and iteratorTimes == 0):
                return 0
            elif isinstance(table, list) is False or len(table) == 0 or (table == "" and iteratorTimes == 1):
                return [{}]
            else:
                return table
        if occurTimes == 1:
            if table == "" and iteratorTimes == 0:
                return 0
            if table is None or isinstance(table, list) is False or len(table) == 0 \
                    or (table == "" and iteratorTimes == 1):
                return [{}]
            else:
                return table
    except:
        return [{}]


def intCheck(str):
    try:
        int(str)
        return True
    except:
        return False

def checkNull(data, accountType):
    if data in null_type_list or data == [{}] or data == 0:
        return 0
    # 账户状态
    PD01BD01 = data[0].get("PD01BD01")
    # 关闭日期
    PD01BR01 = data[0].get("PD01BR01")
    PD01BR01 = dateFormat(PD01BR01)
    # 转出月份
    PD01BR04 = data[0].get("PD01BR04")
    PD01BR04 = dateFormat(PD01BR04)
    fiveYearsAgo = (datetime.datetime.now() - pd.tseries.offsets.DateOffset(years=5)).strftime("%Y%m")
    if accountType == "D1":
        if (PD01BD01 == "3" and PD01BR01 is not None and PD01BR01.strftime("%Y%m") <= fiveYearsAgo) \
                or (PD01BD01 == "5" and PD01BR04 is not None and PD01BR04.strftime("%Y%m") <= fiveYearsAgo):
            return 1
        else:
            return 0
    elif accountType in ["R1", "R4"]:
        if (PD01BD01 == "3" and PD01BR01 is not None and PD01BR01.strftime("%Y%m") <= fiveYearsAgo):
            return 1
        else:
            return 0
    elif accountType in ["R2", "R3"]:
        if (PD01BD01 == "4" and PD01BR01 is not None and PD01BR01.strftime("%Y%m") <= fiveYearsAgo) \
                or (PD01BD01 == "6"):
            return 1
        else:
            return 0
    else:
        return 0

def dateFormat(time):
    import re
    import datetime
    r = re.compile(r'\D+')
    try:
        date = datetime.datetime.strptime(time, '%Y.%m.%d')
    except:
        try:
            date = datetime.datetime.strptime(time, '%Y-%m-%d')
        except:
            try:
                date = datetime.datetime.strptime(time, '%Y/%m/%d')
            except:
                try:
                    tmp = r.sub('', time)
                    date = datetime.datetime.strptime(tmp, '%Y%m%d')
                except:
                    date = None
    return date

# 取出最大月份数，如果字段缺失返回None
def getCount(statusList, month):
    if statusList in null_type_list:
        return -1
    result = 0
    flag = False
    flag2 = False
    for i in statusList:
        try:
            PD01ED01 = i.get("PD01ED01")
            if PD01ED01 not in null_type_list:
                flag = True
                if intCheck(PD01ED01):
                    flag2 = True
                    if month + 1 <= int(PD01ED01) <= 7 and result < int(PD01ED01) - month:
                        result = int(PD01ED01) - month
        except:
            continue
    if flag and flag2:
        return result
    elif flag:
        return 0
    else:
        return None


def pastLoanCardQuasiMaxConOvduMons():
    data = IC_DSJ_2D.get('data')
    factor = []
    # 借贷账户信息 PDA[1.1]
    PDA = getTable(data, 'PDA', 1, 0)
    if PDA == [{}]:
        return u'缺失值'
    elif PDA == 0:
        return 0
    else:
        # 借贷账户信息单元 PD01[0.*]
        PD01 = getTable(PDA[0], 'PD01', 0, 1)
        if PD01 == [{}]:
            return u'缺失值'
        elif PD01 == 0:
            return 0
        else:
            for i in PD01:
                try:
                    # 基本信息段 PD01A[1.1]
                    PD01A = getTable(i, 'PD01A', 1, 1)
                    if PD01A == [{}]:
                        factor.append(None)
                    elif PD01A == 0:
                        factor.append(0)
                    else:
                        # 账号类型
                        PD01AD01 = PD01A[0].get("PD01AD01")
                        # 最近5年内的历史表现信息段 PD01E[0.1]
                        PD01E = getTable(i, 'PD01E', 0, 1)
                        # 最新表现信息段  PD01B  [1..1]
                        PD01B = getTable(i, 'PD01B', 1, 1)

                        if PD01E == [{}]:
                            factor.append(None)
                        elif PD01E == 0:
                            factor.append(0)
                        else:
                            # 获取5年内状态码列表 PD01EH[1.60]
                            PD01EH = getTable(PD01E[0], 'PD01EH', 1, 1)
                            if PD01EH == [{}]:
                                # 进行特殊判断
                                checkRes = checkNull(PD01B, PD01AD01)
                                if checkRes:
                                    factor.append(0)
                                else:
                                    factor.append(None)
                            elif PD01EH == 0:
                                factor.append(0)
                            else:
                                if PD01EH not in null_type_list and PD01AD01 not in null_type_list:
                                    # D1(非循环贷账户), R1(循环贷账户), R2(贷记卡), R4(循环额度下分账户)
                                    if PD01AD01 == "D1" or PD01AD01 == "R1" or PD01AD01 == "R2" or PD01AD01 == "R4":
                                        factor.append(getCount(PD01EH, 0))
                                    elif PD01AD01 == "R3":
                                        factor.append(getCount(PD01EH, 2))
                                    else:
                                        factor.append(0)
                                else:
                                    # 进行特殊判断
                                    checkRes = checkNull(PD01B, PD01AD01)
                                    if checkRes:
                                        factor.append(0)
                                    else:
                                        factor.append(None)
                except:
                    factor.append(None)
                    continue

    factor = [x for x in factor if x is not None]
    if len(factor) == 0:
        return u'缺失值'
    else:
        return max(factor)


if __name__ == '__main__':
    file_obj = open(r'../../data/IC/IC18_PastLoanCardQuasiMaxConOvduMons/IC.json', 'r')
    content = file_obj.read()
    IC_DSJ_2D = json.loads(content, strict=False)
    aa = pastLoanCardQuasiMaxConOvduMons()
    print aa

result = pastLoanCardQuasiMaxConOvduMons()
